package com.carrot.gateway.util;

import org.springframework.http.server.reactive.ServerHttpRequest;

/**
 * @description:
 * @author: zl
 * @date: 2023/11/21
 */
public class IpAddressUtil {

    public static String getClientIpAddress(ServerHttpRequest request) {
        // 从请求头中获取X-Forwarded-For头信息
        String ipAddress = request.getHeaders().getFirst("X-Forwarded-For");

        // 如果X-Forwarded-For为空或者为unknown，则尝试从其他头中获取
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeaders().getFirst("Proxy-Client-IP");
        }

        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeaders().getFirst("WL-Proxy-Client-IP");
        }

        // If the above headers didn't provide a valid IP, try extracting from X-Real-IP header
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeaders().getFirst("X-Real-IP");
        }

        // 如果IP地址包含多个代理的情况，取第一个（逗号分隔）
        int commaPos = (ipAddress != null) ? ipAddress.indexOf(',') : -1;
        if (commaPos > 0) {
            ipAddress = ipAddress.substring(0, commaPos);
        }

        // 如果还是获取不到，使用默认方式
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getRemoteAddress().getHostString();
        }

        return ipAddress.trim();
    }

}
